package com.ljc.ssm.controller;

import com.ljc.ssm.common.JsonResult;
import com.ljc.ssm.utils.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * User: ljc
 * Date: 2022/12/12 21:06
 * Description:
 * Version: V1.0
 *
 * @author: ljc
 */
@RestController

public class UploadController {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpSession session;

    @Autowired
    private ApplicationContext context;
    /**
     * 把上传所需的file,upload给封装在MultipartFile对象
     *
     * @return
     */
    @PostMapping("/upload")
    public JsonResult upload(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) throws IOException {
        System.out.println(multipartFile);
        String originalFilename = multipartFile.getOriginalFilename();
        int pos = originalFilename.lastIndexOf(".");
        String ext = originalFilename.substring(pos + 1);
        String uuidName = UUID.randomUUID().toString().replaceAll("-", "");
        String filename = uuidName + "." + ext;
        System.out.println("fileName" + filename);
        String realPath = session.getServletContext().getRealPath("/");
        String name=realPath+filename;
        File f=new File(name);
        multipartFile.transferTo(f);
        return ResponseUtil.success("success", filename);

    }
}
